package com.walk.zworld.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.location.provider.ProviderProperties;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import com.walk.zworld.view.floatview.utils.SettingsCompat;

public class AllowMockLocationTools {
    private static AllowMockLocationTools singleton;
    private Context mContext;
    private LocationManager locationManager;

    public AllowMockLocationTools(Context context) {
        this.mContext = context;
    }

    public static AllowMockLocationTools with(Context context) {
        if (singleton == null) {
            synchronized (AllowMockLocationTools.class) {
                if (singleton == null) {
                    singleton = new Builder(context).build();
                }
            }
        }

        return singleton;
    }

    public boolean hasLocationPermission(){
        return !(ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED);
    }

    //模拟位置权限是否开启
    public boolean isAllowMockLocation() {
        boolean canMockPosition = true;
        if (ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            SettingsCompat.manageDrawOverlays(mContext);
            return false;
        }
        locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        locationManager.addTestProvider(LocationManager.GPS_PROVIDER, "requiresNetwork" == "", "requiresSatellite" == "", "requiresCell" == "", "hasMonetaryCost" == "", "supportsAltitude" == "", "supportsSpeed" == "", "supportsBearing" == "", ProviderProperties.POWER_USAGE_HIGH, ProviderProperties.ACCURACY_COARSE);
        locationManager.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true);
        locationManager.setTestProviderStatus(LocationManager.GPS_PROVIDER, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000l, 10.0f, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.d("LocationUtils", "onLocationChanged: location=" + location);
            }
        });

        //        try {
//            locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);//获得LocationManager引用
//            String providerStr = LocationManager.GPS_PROVIDER;
//            LocationProvider provider = locationManager.getProvider(providerStr);
//            if (provider != null) {
//                locationManager.addTestProvider(
//                        provider.getName()
//                        , provider.requiresNetwork()
//                        , provider.requiresSatellite()
//                        , provider.requiresCell()
//                        , provider.hasMonetaryCost()
//                        , provider.supportsAltitude()
//                        , provider.supportsSpeed()
//                        , provider.supportsBearing()
//                        , provider.getPowerRequirement()
//                        , provider.getAccuracy());
//            } else {
//                locationManager.addTestProvider(
//                        providerStr
//                        , true, true, false, false, true, true, true
//                        , Criteria.POWER_HIGH, Criteria.ACCURACY_FINE);
//            }
//            locationManager.setTestProviderEnabled(providerStr, true);
//            locationManager.setTestProviderStatus(providerStr, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
//            // 模拟位置可用
//            canMockPosition = true;
//            locationManager.setTestProviderEnabled(providerStr, false);
//            locationManager.removeTestProvider(providerStr);
//        } catch (SecurityException e) {
//            canMockPosition = false;
//        }
        return canMockPosition;
    }

    /**
     * 判断是否打开了允许虚拟位置,android6.0以下及以上都可用
     *
     * @return boolean
     */
    public boolean isAllowMockLocation(Context context) {
        boolean canMockPosition = false;
        if (Build.VERSION.SDK_INT <= 22) {//6.0以下
            canMockPosition = (Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION, 0) != 0);
        } else {
            try {
                LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);//获得LocationManager引用
                String providerStr = LocationManager.GPS_PROVIDER;
                LocationProvider provider = locationManager.getProvider(providerStr);
                if (provider != null) {
                    locationManager.addTestProvider(
                            provider.getName()
                            , provider.requiresNetwork()
                            , provider.requiresSatellite()
                            , provider.requiresCell()
                            , provider.hasMonetaryCost()
                            , provider.supportsAltitude()
                            , provider.supportsSpeed()
                            , provider.supportsBearing()
                            , provider.getPowerRequirement()
                            , provider.getAccuracy());
                } else {
                    locationManager.addTestProvider(
                            providerStr
                            , true, true, false, false, true, true, true
                            , Criteria.POWER_HIGH, Criteria.ACCURACY_FINE);
                }
                locationManager.setTestProviderEnabled(providerStr, true);
                locationManager.setTestProviderStatus(providerStr, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
                // 模拟位置可用
                canMockPosition = true;
            } catch (Exception e) {
                canMockPosition = false;
            }
        }
        return canMockPosition;
    }

    public void setGenerateLocation(float lat, float lng) {
        if (lat == 0) return;
        if (locationManager == null) {
            isAllowMockLocation();
        }
        Location loc = new Location(LocationManager.GPS_PROVIDER);
        loc.setAccuracy(200);
        loc.setAltitude(55.0D);
        loc.setBearing(1.0F);
        Bundle bundle = new Bundle();
        bundle.putInt("satellites", 7);
        loc.setExtras(bundle);
        loc.setLatitude(lat);
        loc.setLongitude(lng);
        loc.setTime(System.currentTimeMillis());
        loc.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
        locationManager.setTestProviderLocation(LocationManager.GPS_PROVIDER, loc);
    }

    public static class Builder{
        private Context context;
        public Builder(Context context) {
            if (context == null) {
                throw new IllegalArgumentException("Context cannot be empty");
            }
            this.context = context.getApplicationContext();
        }

        public AllowMockLocationTools build() {
            return new AllowMockLocationTools(context);
        }
    }
}
